package com.wsoft.utils;

import com.wsoft.config.CachedBodyHttpServletRequest;
import com.wsoft.constant.CommonConstant;
import com.wsoft.vo.LogVO;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Enumeration;

/**
 * @Author z001
 * @Date 2024/11/26 08:41
 */
public class RequestUtil {

    /**
     * 从request中处理日志相关信息
     * @param logVO
     * @param request
     * @throws IOException
     */
    public static void handleLogInfo(LogVO logVO,HttpServletRequest request) throws IOException {
        HttpServletRequest cachedRequest = new CachedBodyHttpServletRequest(request);

        logVO.setUrl(cachedRequest.getRequestURI());
        logVO.setIp(cachedRequest.getRemoteAddr());
        logVO.setCreateTime(String.valueOf(getNowTime()));
        // 获取请求参数
        String requestParams = getRequestParams(cachedRequest);
        logVO.setParamsJson(requestParams);
        logVO.setMethodType(request.getMethod());
    }



    // ################################## 私有方法  ##################################

    /**
     * 获取当前时间的毫秒值
     */
    public static LocalDateTime getNowTime(){
        // 获取当前时间的毫秒值
        long currentTimeMillis = System.currentTimeMillis();
        // 将毫秒值转换为 Instant 对象
        Instant instant = Instant.ofEpochMilli(currentTimeMillis);
        // 将 Instant 对象转换为 LocalDateTime 对象，使用系统默认时区
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     * 获取get/post 请求参数
     * @param request
     * @return
     * @throws IOException
     */
    private static String getRequestParams(HttpServletRequest request) throws IOException {
        StringBuilder params = new StringBuilder();

        // 获取 GET 请求的参数
        if (CommonConstant.HTTP_GET.equalsIgnoreCase(request.getMethod())) {
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = request.getParameter(paramName);
                params.append(paramName).append("=").append(paramValue).append("&");
            }
            if (params.length() > 0) {
                // 去掉最后一个 &
                params.deleteCharAt(params.length() - 1);
            }
        }

        // 获取 POST 请求的参数
        if (CommonConstant.HTTP_POST.equalsIgnoreCase(request.getMethod())) {
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                params.append(line);
            }
        }
        return truncateString(params.toString(),LogUtil.LOG_MAX_LENGTH);
    }

    /**
     * 截取保存数据库最大长度
     * @param str
     * @param maxLength
     * @return
     */
    public static String truncateString(String str, int maxLength) {
        if (str == null || str.length() <= maxLength) {
            return str;
        }
        return str.substring(0, maxLength);
    }

}
